<?php

namespace app\admin\controller\customer;

use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 服务内容
 *
 * @icon fa fa-circle-o
 */
class Audit extends Backend
{
    protected $dataLimit = 'auth'; //默认基类中为false，表示不启用，可额外使用auth和personal两个值
    protected $dataLimitField = 'admin_id';

    /**
     * Intention模型对象
     * @var \app\admin\model\customer\Intention
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\customer\Package();
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            //快速搜索字段
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        $this->searchFields = "create_time";

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(['customer'])
            ->where($where)
            ->orderRaw('field(status,1,3,0,2)')
            ->order($sort, $order)
            ->paginate($limit);

//        $total = [
//            'package_id' => '合计',
//            'customer_id' => 151,
//            'corporate_type' => 0,
//            'signature_url' => '',
//            'signature_time' => 0,
//            'contract_url' => 'contract/contract_66_660634d571162_1711682773.docx',
//            'service_desc' => '无',
//            'pay_type' => 1,
//            'pay_pic' => '',
//            'status' => 0,
//            'audit_remarks' => null,
//            'admin_id' => 1,
//            'account_ids' => '',
//            'outworker_ids' => '',
//            'create_time' => '',
//            'customer' => '',
//            'signature_time_text' => '1970-01-01 08:00:00',
//            'create_time_text' => '-',
//            'service_ids' => [
//                19,
//            ],
//            'service_list' => [],
//            'admin_info' => ['nickname' => '-'],
//            'account_names' => '',
//            'outworker_names' => '',
//            'sales_commission' => 135,
//            'account_commission' => 50,
//            'outworker_commission' => 0,
//            'total_data' => [
//                'standard_price' => 1000,
//                'deal_price' => 500,
//                'cost_price' => 50,
//                'collection_price' => 500,
//                'balance_price' => 0,
//            ],
//        ];
//        $array = $list->items();
//        $array[] = $total;


        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $service_list = Db::name('service')->select();
            $this->assignconfig('service', $service_list);


            return $this->view->fetch('', ['service' => $service_list]);
        }

        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            if (!empty($params['service_ids'])) {
                $params['service_ids'] = implode(',', $params['service_ids']);
            }

            if (!empty($params['start_time'])) {
                $params['start_time'] = strtotime($params['start_time']);
            }

            if (!empty($params['end_time'])) {
                $params['end_time'] = strtotime($params['end_time']);
            }


            $result = $this->model->allowField(true)->save($params);
            $serviceData = [];
            if (!empty($params['serviceTable'])) {
                foreach ($params['serviceTable'] as $item) {
                    $serviceData[] = [
                        'customer_id' => !empty($this->model->id) ? $this->model->id : 0,
                        'service_id' => $item['service_id'],
                        'service_name' => $item['service_name'],
                        'ledger_expenses' => $item['ledger_expenses'],
                        'corporate_type' => $item['corporate_type'],
                        'standard_price' => $item['standard_price'],
                        'cost_price' => $item['cost_price'],
                        'deal_price' => $item['standard_price'],
                    ];
                }
            }
            $result2 = (new \app\admin\model\customer\Service)->allowField(true)->saveAll($serviceData);

            //生成合同
            $this->model->saveCustomerContract($this->model->id);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false || $result2 === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }


    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $service_list = Db::name('service')->select();
            $this->assignconfig('service', $service_list);

            $service = [];
            foreach ($service_list as $item) {
                $service[$item['id']] = $item['service_name'];
            }
            $this->view->assign('service', $service);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            if (!empty($params['service_ids'])) {
                $params['service_ids'] = implode(',', $params['service_ids']);
            }

            if (!empty($params['start_time'])) {
                $params['start_time'] = strtotime($params['start_time']);
            }

            if (!empty($params['end_time'])) {
                $params['end_time'] = strtotime($params['end_time']);
            }
            $serviceData = [];
            if (!empty($params['serviceTable'])) {
                (new \app\admin\model\customer\Service)->where([
                    'customer_id' => $row->id
                ])->delete();
                foreach ($params['serviceTable'] as $item) {
                    $serviceData[] = [
                        'customer_id' => $row->id,
                        'service_id' => $item['service_id'],
                        'service_name' => $item['service_name'],
                        'ledger_expenses' => $item['ledger_expenses'],
                        'corporate_type' => $item['corporate_type'],
                        'standard_price' => $item['standard_price'],
                        'cost_price' => $item['cost_price'],
                        'deal_price' => $item['standard_price'],
                    ];
                }
            }
            (new \app\admin\model\customer\Service)->allowField(true)->saveAll($serviceData);


            $this->model->saveCustomerContract($row->id);

            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function editSale($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }


            $result = $row->allowField(true)->save($params);

            $this->model->generateContract($row->package_id);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    public function details($ids)
    {
        $package = $this->model
            ->with(['customer'])
            ->where([
                'package_id' => $ids
            ])->find();
        if (!$package) {
            return false;
        }

        $package->account_commission = 0;
        $package->sales_commission = 0;
        $package->outworker_commission = 0;
        $package->cost_price = 0;

        foreach ($package->service_list as $item) {
            $package->account_commission += $item['account_commission'];
            $package->sales_commission += $item['sales_commission'];
            $package->outworker_commission += $item['outworker_commission'];
            $package->cost_price += $item['cost_price'];
        }


        $account_list = Db::name('admin')->where(['identity' => 1])->select();
        $outworker_list = Db::name('admin')->where(['identity' => 3])->select();
        $this->assignconfig('account', $account_list);
        $this->assignconfig('outworker', $outworker_list);
        $this->view->assign('row', $package);
        return $this->view->fetch('');
    }

    public function saveAccount($package_id, $account_ids)
    {
        $package = $this->model
            ->where([
                'package_id' => $package_id
            ])->find();
        if (!$package) {
            return false;
        }

        if (!$package->allowField(true)->save(['account_ids' => $account_ids])) {
            $this->error('操作失败');
        }
        $this->success();

    }

    public function saveOutworker($package_id, $outworker_ids)
    {
        $package = $this->model
            ->where([
                'package_id' => $package_id
            ])->find();
        if (!$package) {
            return false;
        }

        if (!$package->allowField(true)->save(['outworker_ids' => $outworker_ids])) {
            $this->error('操作失败');
        }
        $this->success();

    }

    public function saveStatus($ids, $status)
    {
        $package = $this->model::get($ids);
        if (!$package) {
            return false;
        }

        $result = false;
        Db::startTrans();
        try {
            $params['status'] = $status;
            if ($status == 2) {
                $params['audit_time'] = time();
                (new \app\admin\model\customer\Intention())->where(['id' => $package->customer_id])->update(['customer_type' => 1]);
                $list = (new \app\admin\model\customer\Service())->where(['package_id' => $package->package_id])->select();
                foreach ($list as $item) {
                    if ($item->month > 0) {
                        $item->start_time = time();
                        $day = date('d', strtotime("+{$item->month} month"));
                        $item->end_time = strtotime(-$day . ' day');
                        $item->save();
                    }
                }
            }
            $result = $package->allowField(true)->save($params);

            //同步合同
            $this->model->generateContract($package->package_id);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function audit($ids)
    {
        $customer = $this->model::get($ids);
        if (!$customer) {
            return false;
        }
        if (false === $this->request->isPost()) {
            return $this->view->fetch('', ['row' => $customer]);
        }

        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }


        $result = false;
        Db::startTrans();
        try {
            $params['customer_type'] = 1;
            $params['status'] = 0;
            $result = $customer->allowField(true)->save($params);
            if (!empty($params['customer_service'])) {
                foreach ($params['customer_service'] as $item) {
                    (new \app\admin\model\customer\Service())
                        ->where(['id' => $item['id']])
                        ->update(['deal_price' => $item['deal_price']]);
                }
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
